import React, {Component, Fragment} from 'react';
import {Button, Card, Image, Input, message, Space, Table, Tag} from 'antd';
import './less/index.less';
import {MinusOutlined, PlusOutlined, SearchOutlined,} from '@ant-design/icons';
import {Link} from 'react-router-dom';
import {reqBookList} from '../../api/book';
import {dateTimeDateFormat} from '../../utils/tools';

// 表头
// colums设置了dataIndex表示渲染的值
// 如果设置了，render: (text:设置的值) => text
// 没有设置 (text, record) => record:表示整条数据
// render: (text, record, index) => {}，参数分别为当前行的值，当前行数据，行索引。

export default class Books extends Component {
  state = {
    data: [], // 数据
    page: 1, // 页数
    totalCount: 0, // 数据总量
    loading: true, // table加载动画
    selectedRowKeys: [],
  }

  getColumnSearchProps = (dataIndex, title) => ({
    // 设置input框的值 selectedKeys
    // 只负责渲染图层
    // confirm 关闭筛选
    // clearFilters 清空过滤，重新发起请求
    filterDropdown: ({setSelectedKeys, selectedKeys, confirm, clearFilters}) => (
      <div style={{padding: 8}}>
        <Input
          placeholder={`搜索 ${title}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, dataIndex, confirm)}
          style={{width: 188, marginBottom: 8, display: 'block'}}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => this.handleSearch(selectedKeys, dataIndex, confirm)}
            icon={<SearchOutlined/>}
            size="small"
            style={{width: 90}}
          >
            搜索
          </Button>
          <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{width: 90}}>
            重置
          </Button>
        </Space>
      </div>
    ),
    filterIcon: filtered => <SearchOutlined style={{color: filtered ? '#1890ff' : undefined}}/>
  });

  // 点击/回车 搜索
  handleSearch = (selectedKeys, dataIndex, confirm) => {
    confirm(); // 关闭菜单
  };
  // 重置input框
  handleReset = (clearFilters) => {
    clearFilters(); // 重置过滤结果
    this.setState({searchText: ''});
  };

  initColumns = () => {
    this.columns = [
      {
        title: '书名',
        width: 150,
        key: 'name',
        render: item => <Link
          to={{pathname: `/admin/books/list/book/${item._id}`}}>{item.name}</Link>,
        ...this.getColumnSearchProps('name', '书名或作者'),
      },
      {
        title: '作者',
        width: 150,
        dataIndex: 'author',
        key: 'author',
        ellipsis: true,
        render: author => author.join('/')
      },
      {
        title: '出版社',
        width: 150,
        key: 'book_infos.出版社', // 你也可以设置dataIndex后使用(text, record, index)
        render: (item) => item.book_infos['出版社'],
        ellipsis: true,
      },
      {
        title: '出版日期',
        width: 100,
        dataIndex: 'book_infos',
        key: 'book_infos.出版年',
        render: (book_infos) => book_infos['出版年']
      },
      {
        title: '图书封面',
        width: 150,
        render: (text, record) => <Image
          src={record.image}
          width={80}
          title={record.name}
          alt={record.name}/>
      },
      {
        title: 'ISBN',
        dataIndex: 'isbn',
        width: 150,
      },
      {
        title: '标签',
        dataIndex: 'tags',
        width: 150,
        render: (tags) => (
          <>
            {
              tags.map(tag => {
                return (<Tag key={tag}>{tag}</Tag>)
              })
            }
          </>
        )
      },
      {
        title: '下载时间',
        dataIndex: 'download_time',
        width: 150,
        render: (download_time) => dateTimeDateFormat(download_time),
        sorter: true, // 开启排序，参数为函数/true：后端排序
      },
      {
        title: '更新时间',
        width: 150,
        dataIndex: 'update_time',
        render: (update_time) => dateTimeDateFormat(update_time),
        sorter: true,
      }
    ];
  }

  // 初始化table的col参数
  UNSAFE_componentWillMount() {
    this.initColumns();
  }

  // 获取图书数据
  getBooks = async (data = {}) => {
    this.setState({loading: true})
    try {
      const {data: result} = await reqBookList(data);
      this.setState({
        data: result.items,
        totalCount: result.total_count,
        loading: false,
        page: data.page || 1
      }, () => this.scrollTop())
    } catch (e) {
      message.error(e.data.name || e.data.codeName|| e.data.message);
      this.setState({
        loading: false
      })
    }
  }
  // todo
  // 翻页
  changePage = (page, pageSize) => {
    this.getBooks({page, page_size: pageSize})
  }
  // 切换分页
  onShowSizeChange = (current, size) => {
    console.log(current, size)
  }
  // 添加数据
  addClick = () => {
    message.info('不支持添加数据!');
  }
  // 删除数据
  deleteClick = () => {
    if (this.state.selectedRowKeys.length > 0) {

    } else {
      message.warning('请至少选中1条待删除的数据!')
    }
  }
  // 滚动到顶部
  scrollTop = () => {
    const dom = document.querySelector('.ant-layout-content')
    const clock = setInterval(function () { // 滚动过渡
      if (dom.scrollTop !== 0) {
        dom.scrollTop -= 20;
      } else {
        clearInterval(clock);
      }
    }, 10);
  }
  // 选中数据
  onSelectChange = (selectedRowKeys) => {
    this.setState({selectedRowKeys});
  }

  componentDidMount() {
    this.getBooks();
  }

  // table 的参数
  onChange = (pagination, filters, sorter, extra) => {
    const page = pagination.current;
    const pageSize = pagination.pageSize;
    // 由于我的接口是搜索，因此将过滤改为了搜索功能
    const q = filters.name && filters.name[0]; // 查询字段
    const field = sorter.field; // 排序的字段
    let order = sorter.order; // 排序的模式 asc升序 desc降序
    order = order !== undefined ? order.replace('end', '') : 'desc';
    let data = {
      page,
      page_size: pageSize,
      sort: field,
      order,
    }
    data = q ? Object.assign(data, {q}) : data;
    // 当order为undefined时为默认desc
    this.getBooks(data);
  }

  render() {
    const extra = (
      <Fragment>
        <Button type='primary' onClick={this.addClick} icon={<PlusOutlined/>} style={{marginRight: '10px'}}>
          添加
        </Button>
        <Button type='primary' danger onClick={this.deleteClick} icon={<MinusOutlined/>}>
          删除
        </Button>
      </Fragment>
    );

    const {data, totalCount, selectedRowKeys, loading} = this.state;

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    }

    const pagination = {
      position: ['bottomCenter'],
      showQuickJumper: true,
      total: totalCount,
      onShowSizeChange: this.onShowSizeChange
    }
    // sortDirections 三种状态，1 asc 2 desc 3 恢复默认
    // sortDirections 设置该参数，图标就没了
    return (
        <Card title='图书信息' bordered={false} extra={extra}>
          <Table columns={this.columns}
                 loading={loading}
                 rowKey='_id'
                 scroll={{x: 800}}
                 onChange={this.onChange}
                 dataSource={data}
                 rowSelection={rowSelection}
                 pagination={pagination}/>
        </Card>
    )
  }
}


